﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Newtonsoft.Json;

namespace Theta.Serialization
{
    public class JsonSerializer
    {
        public static void Serialize<T>(string path, T obj)
        {
            File.WriteAllText(path, JsonConvert.SerializeObject(obj), Encoding.UTF8);
        }

        public static void Serialize<T>(Stream destStream, T obj)
        {
            string content = JsonConvert.SerializeObject(obj);
            byte[] bc = Encoding.UTF8.GetBytes(content);
            destStream.Write(bc, 0, bc.Length);
        }

        public static T UnSerialize<T>(string path)
        {
            if (!File.Exists(path))
                throw new Exception("Specified file doesn't exist");
            return JsonConvert.DeserializeObject<T>(File.ReadAllText(path));
        }

        public static T UnSerialize<T>(Stream data)
        {
            StreamReader sr = new StreamReader(data);
            string strData = sr.ReadToEnd();
            return JsonConvert.DeserializeObject<T>(strData);
        }
    }
}
